// pages/Release/addinfo/addinfo.js
var app = getApp();
var ikz = require('../../Common/tools.js');
Page({

  /**
   * 页面的初始数据
   */
  data: {
    town_index: 0,//城镇下标
    top_indexs: 0,//置顶下标
    narginbot: 150,//置顶处离底部距离
    tid: '',//所属分类的id
    typ: '',//所属头条或便民（tou或bian）
    shop_info: '',//商家信息（包含红包和发布须知）
    top_info: '',//置顶信息
    town_info: '',//城镇信息
    town_sname: '',//选中城镇名称
    town_sid: '',//选中城镇id
    user_info: '',//用户信息
    istop: '',//显示置顶或优选
    top_sid: '',//选中置顶id
    video_src: '',//选中视频的临时路径
    chooseImgs: [],//选中图片的临时路径列表
    cid: '',//该条信息id
    conven_info: '',//该条信息
    isvideo: 0,//是否改了视频，1是0否
    isimg: 0,//是否改了图片，1是0否
    isdelimg: 0,//是否删除了图片，1是0否
    payway: 2,//支付方式，2余额，3微信
  },
  radioChange: function (e) {
    console.log('radio发生change事件，携带value值为：', e.detail.value);
    this.setData({
      payway: e.detail.value,
    })
  },
  formSubmit: function (e) {
    console.log('form发生了submit事件，携带数据为：', e.detail.value)
    var that = this;
    //获取上传所需信息
    var content = e.detail.value.content;
    var phone = e.detail.value.phone;
    var ni_name = e.detail.value.ni_name;
    var top_sid = that.data.top_sid;
    var town_sid = that.data.town_sid;
    var town_sname = that.data.town_sname;
    var cid = that.data.cid;
    var isvideo = that.data.isvideo;
    var isimg = that.data.isimg;
    var isdelimg = that.data.isdelimg;
    var data = {};
    var video_src = that.data.video_src;
    var chooseImgs = that.data.chooseImgs;
    var payway = that.data.payway;
    if (top_sid == 0) {
      var methodform = 1;//无置顶
    } else {
      if (payway == 2) {
        var methodform = 2;//余额支付
      } else {
        var methodform = 3;//微信支付
      }
    };
    //判断发布人名称不能为空
    if (ni_name == '') {
      wx.showToast({
        title: '请填写发布人名称',
        duration: 2000
      });
      return false;
    };
    //判断内容不能为空
    if (content == '') {
      wx.showToast({
        title: '请填写内容',
        duration: 2000
      });
      return false;
    };
    var re = /^1\d{10}$/;
    //判断电话不能为空
    if (phone == '') {
      wx.showToast({
        title: '请填写联系电话',
        duration: 2000
      });
      return false;
    };
    if (!re.test(phone)) {
      wx.showToast({
        title: '请填写正确电话',
        duration: 2000
      });
      return false;
    };

    var all_data = {
      content: content,
      phone: phone,
      town_sid: town_sid,
      town_sname: town_sname,
      top_sid: top_sid,
      ni_name: ni_name,
      img_url: that.data.conven_info.conven_img,
      video_url: that.data.conven_info.conven_video,
      cid: cid,
    }
    console.log(all_data);
    console.log(123);
    //判断是否有修改视频
    if (isvideo == 0) {
      //判断是否有修改图片
      if (isimg == 1) {
        var path_img = 'Release/upConvenImg';
        var dat = {
          url: path_img,//这里是你图片上传的接口
          path: chooseImgs,//这里是选取的图片的地址数组
        }
        var img_url = [];
        ikz.uploadimgs(data, dat, true, (res) => {
          if (res.data != '') {
            //获取上传图片后的路径
            img_url.push(res.data);
            if (img_url.length == chooseImgs.length) {
              all_data.img_url = img_url.join(',');
              if (methodform == 1) {
                that.upFormWu(all_data);
              } else if (methodform == 2) {
                that.upFormYu(all_data);
              } else if (methodform == 3) {
                that.upFormWx(all_data);
              }
            }
          } else {
            wx.showModal({
              title: '提示',
              content: '服务器繁忙，请稍后重试1！',
              showCancel: false
            })
          }
        })
      } else {
        //判断有删除图片
        if (isdelimg == 1) {
          //判断是否还有剩余图片
          if (chooseImgs.length != 0) {
            //把公共路径截掉
            for (var i = 0; i < chooseImgs.length; i++) {
              chooseImgs[i] = chooseImgs[i].slice(25);
            }
            all_data.img_url = chooseImgs.join(',');
            if (methodform == 1) {
              that.upFormWu(all_data);
            } else if (methodform == 2) {
              that.upFormYu(all_data);
            } else if (methodform == 3) {
              that.upFormWx(all_data);
            }
          } else {
            all_data.img_url = '';
            if (methodform == 1) {
              that.upFormWu(all_data);
            } else if (methodform == 2) {
              that.upFormYu(all_data);
            } else if (methodform == 3) {
              that.upFormWx(all_data);
            }
          }
        } else {
          if (methodform == 1) {
            that.upFormWu(all_data);
          } else if (methodform == 2) {
            that.upFormYu(all_data);
          } else if (methodform == 3) {
            that.upFormWx(all_data);
          }
        }

      }
    } else {
      var path = 'Release/upConvenVideo';
      ikz.up(path, data, 'video_info', video_src, true, (res) => {
        console.log(res);
        if (res.data != '') {
          //获取上传视频后的路径
          var video_url = res.data;
          all_data.video_url = video_url;
          //判断是否有修改图片
          if (isimg == 1) {
            var path_img = 'Release/upConvenImg';
            var dat = {
              url: path_img,//这里是你图片上传的接口
              path: chooseImgs,//这里是选取的图片的地址数组
            }
            var img_url = [];
            ikz.uploadimgs(data, dat, true, (res) => {
              if (res.data != '') {
                //获取上传图片后的路径
                img_url.push(res.data);
                if (img_url.length == chooseImgs.length) {
                  all_data.img_url = img_url.join(',');
                  if (methodform == 1) {
                    that.upFormWu(all_data);
                  } else if (methodform == 2) {
                    that.upFormYu(all_data);
                  } else if (methodform == 3) {
                    that.upFormWx(all_data);
                  }
                }
              } else {
                wx.showModal({
                  title: '提示',
                  content: '服务器繁忙，请稍后重试1！',
                  showCancel: false
                })
              }
            })
          } else {
            //判断有删除图片
            if (isdelimg == 1) {
              //判断是否还有剩余图片
              if (chooseImgs.length != 0) {
                //把公共路径截掉
                for (var i = 0; i < chooseImgs.length; i++) {
                  chooseImgs[i] = chooseImgs[i].slice(25);
                }
                all_data.img_url = chooseImgs.join(',');
                if (methodform == 1) {
                  that.upFormWu(all_data);
                } else if (methodform == 2) {
                  that.upFormYu(all_data);
                } else if (methodform == 3) {
                  that.upFormWx(all_data);
                }
              } else {
                all_data.img_url = '';
                if (methodform == 1) {
                  that.upFormWu(all_data);
                } else if (methodform == 2) {
                  that.upFormYu(all_data);
                } else if (methodform == 3) {
                  that.upFormWx(all_data);
                }
              }
            } else {
              if (methodform == 1) {
                that.upFormWu(all_data);
              } else if (methodform == 2) {
                that.upFormYu(all_data);
              } else if (methodform == 3) {
                that.upFormWx(all_data);
              }
            }

          }
        } else {
          wx.showModal({
            title: '提示',
            content: '服务器繁忙，请稍后重试1！',
            showCancel: false
          })
        }
      });
    };
  },

  //无置顶上传方法
  upFormWu(data) {
    var path = 'Percenter/addConvenInfoWu';
    ikz.request(path, data, true, (res) => {
      if (res.data.status == 'success') {
        wx.showModal({
          title: '提示',
          content: '修改成功！',
          showCancel: false
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '服务器繁忙，请稍后重试！',
          showCancel: false
        })
      }
    });
  },
  //余额支付上传方法
  upFormYu(data) {
    var path = 'Percenter/addConvenInfoYu';
    wx.showModal({
      title: '提示',
      content: '确认用余额支付？',
      success: function (res) {
        if (res.confirm) {
          var that = this;
          ikz.request(path, data, true, (res) => {
            if (res.data.status == 'success') {
              wx.showModal({
                title: '提示',
                content: '修改成功！',
                showCancel: false
              })
            } else if (res.data.status == 'nomoney') {
              wx.showModal({
                title: '提示',
                content: '修改失败，余额不足！',
                showCancel: false
              })
            } else {
              wx.showModal({
                title: '提示',
                content: '服务器繁忙，请稍后重试！',
                showCancel: false
              })
            }
          });
        } else if (res.cancel) {
          return false;
        }
      }
    })

  },
  //微信支付上传方法
  upFormWx(data) {
    var path = 'Percenter/addConvenInfoWx';
    wx.showModal({
      title: '提示',
      content: '您确认支付吗？',
      success: function (res) {
        if (res.confirm) {
          var that = this;
          ikz.request(path, data, true, (res) => {
            console.log(res.data);
            console.log(233444);
            if (res.data.status == 'success') {
              console.log(res.data)
              var payment = res.data.pay;
              var outnum = res.data.out_num;
              ikz.pay(payment, (res) => {
                //提示 并跳转
                wx.showModal({
                  title: '提示',
                  content: '查看支付结果',
                  success: function (res) {
                    console.log(res);
                    if (res.confirm) {
                      var path = 'Release/checkHeadOr';
                      var data = {
                        num: outnum
                      }
                      ikz.request(path, data, true, (res) => {
                        if (res.data == 'success') {
                          wx.showModal({
                            title: '提示',
                            content: '支付成功！',
                            showCancel: false
                          })
                        } else {
                          wx.showModal({
                            title: '提示',
                            content: '支付失败，请重试',
                            showCancel: false
                          })
                        }
                      })
                    }
                  }
                })
              })
            } else {
              wx.showModal({
                title: '提示',
                content: '服务器繁忙，请稍后重试！',
                showCancel: false
              })
            }
          });
        } else if (res.cancel) {
          return false;
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var cid = options.cid;
    this.setData({
      cid: cid,
    })
    var data = {
      cid: cid,
    };
    var that = this;
    ikz.over(that);
    var path = 'Percenter/releaseConvenInfo';
    ikz.request(path, data, true, (res) => {
      console.log(res.data);
      if (res.data.status == 'success') {
        //找到默认城镇及其下标
        var town_sid = res.data.conven_info['conven_town_id'];
        var town_sname = res.data.conven_info['conven_town_name'];
        var town_info = res.data.town_info;
        if (town_info.length) {
          for (var i = 0; i < town_info.length; i++) {
            if (town_sid == town_info[i]['town_id']) {
              var town_index = i;
            }
          };
        }
        //找到默认置顶及其下标
        var top_info = res.data.top_info;
        var top_sid = res.data.conven_info['conven_top_id'];
        if (top_info.length) {
          for (var i = 0; i < top_info.length; i++) {
            if (top_sid == top_info[i]['top_id']) {
              var top_indexs = i;
              break;
            } else {
              var top_indexs = 0;
            }
          };
        }
        
        //找到默认视频
        var video_src = res.data.conven_info['conven_videos'];
        //找到默认图片
        var chooseImgs = res.data.conven_info['conven_imgs'];
        that.setData({
          user_info: res.data.user_info,
          top_info: res.data.top_info,
          town_info: res.data.town_info,
          conven_info: res.data.conven_info,
          town_sid: town_sid,
          town_sname: town_sname,
          town_index: town_index,
          chooseImgs: chooseImgs,
          video_src: video_src,
          top_sid: top_sid,
          top_indexs: top_indexs,
          payway: res.data.conven_info['conven_top_payway'],
        })
      } else {
        wx.showModal({
          title: '提示',
          content: '服务器繁忙，请稍后重试！',
          showCancel: false
        })
      }

    });
  },


  //选择图片
  chooseImg: function () {
    var that = this;
    wx.chooseImage({
      count: 15, // 默认9
      sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
      success: function (res) {
        // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
        var chooseImgs = res.tempFilePaths;
        console.log(chooseImgs);
        that.setData({
          chooseImgs: chooseImgs,
          isimg: 1,
        })
      }
    })
  },
  //删除图片
  cancleImg: function (e) {
    var idx = e.target.dataset.idx;
    var chooseImgs = this.data.chooseImgs;
    chooseImgs.splice(idx, 1);
    this.setData({
      chooseImgs: chooseImgs,
      isdelimg: 1,
    })
  },
  //获取视频
  bindButtonTap: function () {
    var that = this;
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success: function (res) {
        that.setData({
          video_src: res.tempFilePath,
          isvideo: 1,
        })
      },
      fail: function (res) {
        console.log(4545)
      }
    })
  },
  //置顶选择
  topChange: function (e) {
    var top_ind = e.detail.value;
    var top_info = this.data.top_info;
    if (top_info.length) {
      for (var i = 0; i < top_info.length; i++) {
        if (top_ind == i && i > 0) {
          var top_sid = top_info[i]['top_id'];
        }
        if (top_ind == 0) {
          var top_sid = '';
        }
      };
    }

    this.setData({
      top_indexs: e.detail.value,
      top_sid: top_sid,
    })
  },
  //城镇地址选择
  townChange: function (e) {
    var town_ind = e.detail.value;
    var town_info = this.data.town_info;
    if (town_info.length) {
      for (var i = 0; i < town_info.length; i++) {
        if (town_ind == i) {
          var town_sid = town_info[i]['town_id'];
          var town_sname = town_info[i]['town_name'];
        }
      };
    }
    this.setData({
      town_index: e.detail.value,
      town_sid: town_sid,
      town_sname: town_sname,
    })
  },
  


  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    ikz.hide(this);
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})